package com.ulk.systempermission.utils;

import android.app.ActivityManager;
import android.content.Context;

import com.ulk.corelib.utils.apk.ApkUtils;
import com.ulk.corelib.utils.log.LogUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * the process utils class.
 *
 * @author xuxiaohong
 * @date 2016/7/19
 */
public class ProcessUtils {

    /**TAG*/
    private static final String TAG = "ProcessUtils";

    /**杀死指定包名的进程*/
    public static void killProcess(Context context, String packageName) {
        if (null == context) {
            return;
        }

        if (isProcessRunning(context, packageName)) {
            ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            if (null != am) {
                try {
                    LogUtils.wtf(TAG, "PowerUtils#killProcess packageName = " + packageName);
                    Method forceStopPackage = am.getClass().getDeclaredMethod("forceStopPackage", String.class);
                    forceStopPackage.setAccessible(true);
                    forceStopPackage.invoke(am, packageName);
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**指定进程是否正在运行*/
    public static boolean isProcessRunning(Context context, String packageName) {
        return ApkUtils.isProcessRunning(context, packageName);
    }
}
